import axios from "axios"; // 引用axios
import config from "@/api/config";
import {
	ElMessage
} from 'element-plus'
import router from '@/router'
const instance = axios.create({
	baseURL: config.baseUrl.dev,
	timeout: 60000,
});


//请求拦截
instance.interceptors.request.use(function(config) {
	// console.log(config)
	let token = sessionStorage.getItem("accessToken");
	if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
		config.headers.loginToken = token;
	}
	return config
}, function(error) {
	return Promise.reject(error)
});


//响应拦截
instance.interceptors.response.use(function(response) {
	// console.log(response)
	return response
}, function(error) {
	if (error.response.status == 401 || error.response.status == 402) {
		ElMessage.error('登陆失败');
		router.push('/login')
	}
	console.log(error)
	return Promise.reject(error)
});



//post请求
export function post(url, data = {}, config = {}) {
	return new Promise((resolve, reject) => {
		// 判断是否传递了文件对象
		if (data.file) {
			const formData = new FormData();

			// 将普通数据字段添加到 FormData
			for (const key in data) {
				if (key !== 'file') {
					formData.append(key, data[key]);
				}
			}

			// 添加文件到 FormData
			formData.append('file', data.file);

			instance.post(url, formData, config).then(
				(response) => {
					resolve(response.data);
				},
				(err) => {
					reject(err);
				}
			);
		} else {
			// 如果没有文件，继续使用原来的方式发送请求
			instance.post(url, data, config).then(
				(response) => {
					resolve(response.data);
				},
				(err) => {
					reject(err);
				}
			);
		}
	});
}
//get请求
export function get(url, params = {}, config = {}) {
	return new Promise((resolve, reject) => {
		instance
			.get(url, {
				params: params,
			}, config)
			.then((response) => {
				resolve(response);
			})
			.catch((err) => {
				reject(err);
			});
	});
}